import pathlib

import uvicorn
import pytest
from fastapi import FastAPI, Request, BackgroundTasks
from fastapi.templating import Jinja2Templates
from starlette.responses import RedirectResponse

app = FastAPI()
template = Jinja2Templates("pages")


@app.get("/")
def index(req: Request):
    current_dir = pathlib.Path(__file__).resolve().parent
    workspace = current_dir / 'workspace'
    projects = [
        {
            "name": project_path.name,
            "url": f"http://localhost:8000/projects/{project_path.name}",
            "path": project_path
        }
        for project_path in workspace.iterdir()
    ]
    return template.TemplateResponse("jenkans_home.html", context={"request": req, "projects": projects})


def run_test(name):
    """build project"""
    pytest.main([f"workspace/{name}"])


@app.get("/projects/{name}")
def run_project(name, task: BackgroundTasks):
    task.add_task(run_test, name)
    return RedirectResponse("/")


if __name__ == '__main__':
    uvicorn.run(app)
